package com.aerospace.example.hello;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName HelloWorldClient
 * @Description
 * @Author yuhang11
 * @Date 2021/7/8 2:22 下午
 * @Version 1.0
 */
@Slf4j
public class HelloWorldClient {
    private final GreeterGrpc.GreeterBlockingStub blockingStub;

    public static void main(String[] args) throws InterruptedException {
        String user = "world";
        String target = "localhost:50051";
        if (args.length > 0){
            if ("--help".equals(args[0])){
                log.info("Usage: [name [target]]");
                log.info("name The name you wish to be greeted by. Defaults to " + user);
                log.info("target  The server to connect to. Defaults to " + target);
                System.exit(1);
            }
            user = args[0];
        }
        if (args.length > 1){
            target = args[1];
        }
        //建立channel，线程安全，可重用
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target).usePlaintext().build();
        try {
            HelloWorldClient client = new HelloWorldClient(channel);
            client.greet(user);
        }finally {
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }

    //阻塞的stub
    private HelloWorldClient(Channel channel){
        blockingStub  = GreeterGrpc.newBlockingStub(channel);
    }

    //调用server端sayHello方法
    public void greet(String name){
        log.info("Will try to greet " + name + "...");
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        }catch (Exception e){
            e.printStackTrace();
            return;
        }
        log.info("Greeting:" + response.getMessage());
    }
}
